﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;


namespace OCSMgmt
{
    class MOC
    {
        static public UsersCollection GetGroupMembers(String UserInstanceID, System.UInt32 GroupInstanceID)
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();
                
                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM MSFT_SIPESUserContactData WHERE UserInstanceID='" + UserInstanceID + "'");

                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
                UsersCollection u = new UsersCollection();
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    System.UInt32[] j = (UInt32[])queryObj["GroupID"];
                    if (j != null && j[0] == GroupInstanceID)
                    {
                        u.Add(new User("", queryObj["SIPURI"].ToString(), true, "", ""));
                    }
                }
                return u;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
            }

        }
        static public GroupsCollection GetGroupsForUser(String UserInstanceID) 
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM MSFT_SIPESUserContactGroupData WHERE UserInstanceID='" + UserInstanceID + "'");

                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
                GroupsCollection g = new GroupsCollection();
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    g.Add(new Group("", queryObj["GroupID"].ToString(), queryObj["Name"].ToString(), queryObj["UserInstanceID"].ToString()));
                }
                return g;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message); 
            }
        }
        static public UsersCollection GetUsers()
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:"+ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\"+ConfigOptions.server+"\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM MSFT_SIPESUserSetting");

                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
                UsersCollection u = new UsersCollection();
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    u.Add(new User( queryObj["UserDN"].ToString(),
                                    queryObj["PrimaryURI"].ToString(),
                                    true, 
                                    queryObj["DisplayName"].ToString(),
                                    queryObj["InstanceID"].ToString()
                                    ));
                }
                return u;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message); 
            }
        }
        static public void DeleteContact(string UserInstanceID, string PrimaryURI) 
        { 
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM MSFT_SIPESUserContactData WHERE UserInstanceID='" + UserInstanceID + "'");

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if ((PrimaryURI.ToLower() == queryObj["SIPURI"].ToString().ToLower()) || PrimaryURI.Length==0) 
                    {
                        queryObj.Delete();
                    }
                }
                return ;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
            }


        }
        static public void DeleteGroups(String UserInstanceID,String GroupName)
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM MSFT_SIPESUserContactGroupData WHERE UserInstanceID='" + UserInstanceID + "'");

                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj["Name"].ToString() == GroupName || GroupName.Length==0)
                    {
                        queryObj.Delete();
                    }
                    
                }
                return;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
            }
        }
        static public void CreateGroup(String UserInstanceID, String GroupName)
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();
                ManagementPath managementpath = new ManagementPath("MSFT_SIPESUserContactGroupData");
                PutOptions po = new PutOptions();
                ObjectGetOptions ogo = new ObjectGetOptions();
                po.Type = PutType.CreateOnly;

                ManagementObject ContactGroup = new ManagementClass(scope, managementpath, ogo).CreateInstance();

                ContactGroup.Properties["UserInstanceID"].Value = UserInstanceID;
                ContactGroup.Properties["Name"].Value = GroupName;
                try
                {
                    ContactGroup.Put(po);
                }
                catch 
                {
                    throw new Exception("Group \"" +GroupName+ "\" already exist");
 
                }
                return;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
            }
        }
        static public void AddContact(String UserInstanceID,string PrimaryURI, String GroupName)
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();
                ManagementPath managementpath = new ManagementPath("MSFT_SIPESUserContactData");
                ObjectGetOptions ogo = new ObjectGetOptions();
                ManagementObject Contact = new ManagementClass(scope, managementpath, ogo).CreateInstance();

                Contact.Properties["UserInstanceID"].Value = UserInstanceID;
                Contact.Properties["SIPURI"].Value = PrimaryURI;
                Contact.Properties["Subscribed"].Value = "true";
                string GroupID =GetGroupID(UserInstanceID, GroupName);
                if (GroupID!= null) 
                {
                    System.UInt32[] j={0} ;
                    j[0] = Convert.ToUInt32(GroupID);
                    Contact.Properties["GroupID"].Value = j;
                }
                try
                {
                    Contact.Put();
                }
                catch( Exception ex)
                {
                    throw new Exception("Error adding contact " + PrimaryURI + " Erro: " +ex.Message );

                }
                return;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
            }
        }
        static public String GetGroupID(String UserInstanceID, String GroupName)
        {
            try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = ConfigOptions.username;
                connection.Password = ConfigOptions.password;
                connection.Authority = "ntlmdomain:" + ConfigOptions.domain;

                ManagementScope scope = new ManagementScope(
                    "\\\\" + ConfigOptions.server + "\\root\\CIMV2", connection);
                scope.Connect();

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM MSFT_SIPESUserContactGroupData WHERE UserInstanceID='" + UserInstanceID + "'");

                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj["Name"].ToString() == GroupName)
                    {
                        return queryObj["GroupID"].ToString();
                    }
                }
                return null;
            }
            catch (ManagementException err)
            {
                throw new ManagementException("An error occurred while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                throw new UnauthorizedAccessException("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
            }
        }
    }
}
